<!-- 地图编辑功能  作业范围分配 -->
<template>
  <div class="map-content">
    <div class="app-container">
      <el-card
        shadow="never"
        class="card-box"
      >
        <!--表头 -->
        <div class="header-box">
          <span>作业范围分配</span>
          <div style="float: right">
            <!-- 编辑 -->
            <el-button
              v-show="editShow"
              class="edit-save-btn"
              @click="btnEdit"
            >编辑</el-button>
            <!-- 保存 -->
            <el-button
              v-show="!editShow"
              class="edit-save-btn"
              @click="btnSave"
            >保存</el-button>
            <!-- 取消按钮 -->
            <el-button
              v-show="!editShow"
              class="cancel-map-btn"
              @click="btnCancel"
            >取消</el-button>
          </div>
        </div>

        <!-- 搜索框 -->
        <div class="searchBox">
          <div class="keyword">
            <label>地区关键词：</label>
            <el-input
              v-model="keyword"
              placeholder="请输入地区关键词"
              @input="changeInput"
            />
          </div>
        </div>

        <!-- 地图 -->
        <div class="map">
          <div
            v-show="!editShow || ApiData.polygon === null"
            class="myDialog"
          >
            <el-button
              v-show="oneShow"
              class="draw-btn"
              @click="btnDraw"
            >开始绘制</el-button>
            <el-button
              v-show="secondShow"
              class="draw-btn"
              @click="btnFinish"
            >
              完成绘制
            </el-button>
            <el-button
              v-show="secondShow"
              class="cancel-map-btn"
              @click="btnDelete"
            >
              删除围栏
            </el-button>
            <div
              v-show="!editShow || !ApiData.polygon"
              class="tip"
            >
              <p v-show="!editShow">
                点击或拖动鼠标绘制电子围栏，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。仅支持绘制单个电子围栏区域
              </p>
              <p v-show="!ApiData.polygon && editShow">
                当前{{ $route.query.agencyName }}营业部下暂无作业范围
              </p>
            </div>
          </div>
          <!-- 地图组件 -->
          <div class="map-module">
            <div id="container"></div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 获取快递员/机构作业范围,type(1:机构,2:快递员)
import { courierScopeList, deleteCourierScope, courierAdd } from '@/api/branch'
export default {
  data() {
    return {
      addFlag: true,
      ApiData: {
        // created: null,
        bid: null,
        longitude: null,
        latitude: null,
        // updated: null,
        type: 2,
        polygon: null
      },
      newAreaData: [],
      polygon: null,
      // 多边形数据
      AreaData: null,
      // 控制显示隐藏
      editShow: true,
      oneShow: false,
      secondShow: false,
      // 搜索框关键字
      keyword: '',
      map: null,
      p: []
    }
  },
  async mounted() {
    // // 发送请求获取数据
    const { data } = await courierScopeList(this.$route.query.id, 2)
    this.ApiData.longitude = data.longitude
    this.ApiData.latitude = data.latitude
    this.ApiData.polygon = data.polygon
    // this.ApiData.created = Number(data.created)
    this.ApiData.bid = data.bid
    // 判断有无员工营业范围
    if (data.polygon) {
      // 折线图数据
      const polygonData = this.ApiData.polygon.map(item => {
        return new BMap.Point(item.longitude, item.latitude)
      })
      // 百度地图API功能
      this.map = new BMap.Map('container')
      var point = new BMap.Point(this.ApiData.longitude, this.ApiData.latitude)
      this.map.centerAndZoom(point, 10)
      this.map.enableScrollWheelZoom()
      // // 创建多边形
      this.polygon = new BMap.Polygon(polygonData, {
        strokeColor: 'red',
        fillColor: '#f9c39e',
        strokeStyle: 'dashed',
        strokeWeight: 2,
        strokeOpacity: 0.5
      }) // 创建多边形
      this.map.addOverlay(this.polygon) // 增加多边形
    } else {
      // 百度地图API功能
      // eslint-disable-next-line no-redeclare
      this.map = new BMap.Map('container')
      // eslint-disable-next-line no-redeclare
      var point = new BMap.Point(this.ApiData.longitude, this.ApiData.latitude)
      this.map.centerAndZoom(point, 10)
      this.map.enableScrollWheelZoom()
    }
    this.addFlag = !this.ApiData.polygon
  },
  methods: {
    // 地址搜索
    changeInput() {
      // 百度地图API功能
      var map = new BMap.Map('container')
      var myGeo = new BMap.Geocoder()
      // 将地址解析结果显示在地图上,并调整地图视野
      myGeo.getPoint(
        this.keyword,
        function(point) {
          if (point) {
            map.centerAndZoom(point, 10)
            map.addOverlay(new BMap.Marker(point))
            map.enableScrollWheelZoom()
          }
        },
        this.keyword
      )
    },
    // 点击保存
    async btnSave() {
      try {
        const fakeNewAreaData = this.polygon.getPath()
        // console.log(fakeNewAreaData[0].lat)
        // console.log(fakeNewAreaData[fakeNewAreaData.length - 1].lat)
        if (
          fakeNewAreaData[0].lat !==
            fakeNewAreaData[fakeNewAreaData.length - 1].lat &&
        fakeNewAreaData[0].lng !==
          fakeNewAreaData[fakeNewAreaData.length - 1].lng
        ) {
          fakeNewAreaData.push(fakeNewAreaData[0])
        }
        fakeNewAreaData.forEach(item => {
          const obj = {
            latitude: null,
            longitude: null
          }

          obj.latitude = item.lat.toFixed(6)
          obj.longitude = item.lng.toFixed(6)
          this.newAreaData.push(obj)
        })
        // if (!this.ApiData.created) {
        //   this.ApiData.created = +new Date()
        // }
        this.ApiData.bid = this.$route.query.id
        this.ApiData.polygon = this.newAreaData
        // this.ApiData.updated = +new Date()
        const res = await courierAdd(this.ApiData)
        if (res.code === 1) {
          return this.$message.error('修改失败')
        }
        this.polygon.disableEditing()
        this.newAreaData = []
        this.secondShow = false
        this.oneShow = true
        this.editShow = true
        this.$message.success('修改成功')
      } catch (error) {
        return this.$message.error('保存失败')
      }
    },
    // 点击完成绘制
    btnFinish() {
      this.secondShow = false
      this.oneShow = true
      this.polygon.disableEditing()
    },
    // 点击删除
    async btnDelete() {
      try {
        if (this.polygon) {
          await deleteCourierScope(this.$route.query.id, 2)
          this.polygon = null
          this.p = []
          this.map.clearOverlays(this.polygon)
          this.oneShow = true
          this.secondShow = false
          this.editShow = true
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
        // 重新渲染
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    // 点击开始绘制
    btnDraw() {
      this.secondShow = true
      this.oneShow = false
      if (this.polygon) {
        this.polygon.enableEditing()
      } else {
        // eslint-disable-next-line no-unused-vars
        var e1, e2
        var doneDraw = true // 判断是否绘制折线结束
        this.map.addEventListener('click', e1 => {
          console.log(e1)
          // 当鼠标单击时
          if (doneDraw) {
            // 判断是否绘制曲线完毕
            this.p.push(new BMap.Point(e1.point.lng, e1.point.lat)) // 存储曲线上每个点的经纬度
            if (this.polygon) {
              this.polygon.setPath(this.p)
            // eslint-disable-next-line brace-style
            } // 如果曲线存在，则获取折线上的点
            else {
              this.polygon = new BMap.Polygon(this.p, {
                strokeColor: 'red',
                fillColor: '#f9c39e',
                strokeStyle: 'dashed',
                strokeWeight: 2,
                strokeOpacity: 0.5
              })
            } // 如果折线不存在，就增加此点
            if (this.p.length >= 1) {
              this.map.addOverlay(this.polygon) // 绘制曲线
              this.polygon.enableEditing()
            } // 当折线上的点只有一个时，不绘制
          }
        })
        // this.map.addEventListener('dblclick', (e2) => { // 当鼠标双击时：结束绘制，并可以编辑曲线
        //   alert('绘制完成')
        //   doneDraw = false
        //   this.polygon.enableEditing()
        // })
      }
    },
    // 点击编辑
    btnEdit() {
      this.editShow = false
      this.oneShow = true
    },
    // 点击取消
    btnCancel() {
      this.editShow = true
      this.oneShow = false
      this.secondShow = false
      this.polygon.disableEditing()
    }
  }
}
</script>

<style lang="scss" scoped>
.map-content {
  .card-box {
    // el-card
    border-radius: 4px;
    ::v-deep .el-card__body {
      padding: 0;
    }
    // 表头
    .header-box {
      padding: 0 25px;
      border-bottom: 0;
      background: #f8faff;
      font-size: 16px;
      font-weight: 700;
      color: #2a2929;
      height: 60px;
      line-height: 60px;
      .edit-save-btn {
        background-color: #e15536;
        color: #ffffff;
        width: 90px;
        border-radius: 5px;
        font-weight: 400;
        border: 1px solid #e15536;
        &:hover {
          background: #ffab98;
          border: 1px solid #ffab98;
        }
      }
      .cancel-map-btn {
        width: 90px;
        color: #2a2929;
        border: 1px solid #d8dde3;
        border-radius: 5px;
        font-weight: 400;
        &:hover {
          background: #ffeeeb;
          border: 1px solid #f3917c;
          color: #e15536;
        }
      }
    }
    // 搜索框
    .searchBox {
      display: flex;
      padding-left: 25px;
      padding-top: 20px;
      label {
        color: #20232a;
        font-weight: 400;
        font-size: 14px;
      }
      ::v-deep .el-input {
        width: 230px;
      }
      .keyword {
        margin-right: 30px;
      }
    }
    // 地图框
    .map {
      padding: 20px;
      height: 600px;
      .myDialog {
        z-index: 999;
        background-color: white;
        width: 100%;
        .draw-btn {
          background-color: #e15536;
          color: #ffffff;
          width: 90px;
          border-radius: 5px;
          font-weight: 400;
          border: 1px solid #e15536;
          &:hover {
            background: #ffab98;
            border: 1px solid #ffab98;
          }
        }
        .tip {
          margin: 10px 0 10px;
          padding: 5px;
          background-color: #fff5e7;
          p {
            margin: 0;
            font-size: 12px;
            color: rgb(198, 126, 18);
            &::before {
              content: ' ';
              display: inline-block;
              width: 12px;
              height: 12px;
              background: url('../../../assets/warn.png') no-repeat;
              background-size: 12px 12px;
            }
            &:nth-of-type(2) {
              text-align: center;
            }
          }
        }
      }
      .map-module {
        width: 100%;
        height: 520px;
        #container {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
